#import "LazyView.h"
#import "LazyWraps.h"

#define SWAITTIME 1000		// wait 1 second
#define WAITMAX 60		// max. time until next move in seconds
#define R(max)	(random()&1023)/1024.0*(max)	// generate random number r, 0 <= r < max
#define FONT "Helvetica-BoldOblique"

@implementation LazyView

+ initialize
{
    srandom(time(0));
    return self;
}

- oneStep
{
    time_t t = time(0);

    if (![self timePassed: SWAITTIME])
	return self;
    
    timestr = ctime(&t);

    PSWclearrect(x, y - 0.25 * size, size * 12.7, size * 1.05);		// delete old text
   
    if(--ticks <= 0) {		// if we have to move...
	float tsx;		// text width
	
	ticks = (int)R(WAITMAX)+10;	// wait random time t until next move
	size = floor(R(ms)) + 20;	// new random size within bounds
	tsx = 12.5 * size;		// this is the approx. text width
	x = R(mx-tsx);			// calc. position for text in screen
	y = R(my-size) + size * 0.3;	// same for y and correct for chars like `g' (approx.)
	r = R(0.8) + 0.2;		// calc. random color which is not too dark
	g = R(0.8) + 0.2;
	b = R(0.8) + 0.2;
	[actFont = [Font newFont:FONT size:size matrix:NX_IDENTITYMATRIX] set];
	PSWshowtext(timestr, x, y, r, g, b);
    } else {
	PSWshowtext(timestr, x, y, r, g, b);
    }
    return self;
}

- initFrame:(NXRect *)frameRect
{
	ticks = 0;
	x = y = 0;

	[super initFrame:frameRect];
	[self setClipping:NO];		// not needed and faster...
	actFont = [Font newFont:FONT size:30.0 matrix:NX_IDENTITYMATRIX];
	[self newSize];
	return self;
}

- sizeTo:(NXCoord)width :(NXCoord)height
{
	[super sizeTo:width :height];
	[self newSize];
	return self;
}

- drawSelf:(const NXRect *)rects :(int)rectCount
{
	if (!rects || !rectCount) return self;

	PSsetgray(0);
	NXRectFill(rects);
	ticks = 0;

	return self;
}

- didLockFocus	// if we're lockFocused we have to reset the font
{
	[actFont set];
	return self;
}

- newSize		// this keeps the size legal
{
	mx = bounds.size.width;
	my = bounds.size.height;
	ms = mx/12.5 - 22;
	ticks = 0;
	return self;
}

- (const char *)windowTitle
{
	return "Lazy";
}

- inspector:sender
{
    char buf[MAXPATHLEN];
	
    if (!infoView) {
	[NXBundle getPath:buf forResource:"Info" ofType:"nib" inDirectory:[sender moduleDirectory:"Lazy"] withVersion:0];
	[NXApp loadNibFile:buf owner:self withNames:NO];
    }

    return infoView;
}

@end
